<script setup lang="ts">
import { useSendMobileCode } from '@/composable'
import { bindMobile, loginByQQ } from '@/services/user'
import { useUserStore } from '@/stores'
import type { User } from '@/types/user'
import { codeRules, mobileRules } from '@/utils/rules'
import { showSuccessToast } from 'vant'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

/**
 * 需求 获取openId
 * 方法名	            参数	    返回	        描述
 * QC.Login.check方法	无	        Boolean	       检查是否已经登录
 * QC.Login.getMe	    Function	无	        回调函数 function(openId, accessToken) openId：用户身份的唯一标识
 */
const openId = ref('')
const isNeedBind = ref(false)
onMounted(() => {
  const isLogin = window.QC.Login.check()
  // console.log(isLogin)
  if (isLogin) {
    window.QC.Login.getMe(async (id) => {
      // console.log(id)
      openId.value = id
      try {
        const { data } = await loginByQQ(openId.value)
        console.log(data)
        loginSuccess(data)
      } catch (error) {
        isNeedBind.value = true
      }
    })
  }
})
const userStore = useUserStore()
const router = useRouter()
const loginSuccess = (data: User) => {
  showSuccessToast('登录成功')
  userStore.setUser(data)
  const returnUrl = userStore.returnUrl
  router.replace(returnUrl || '/user')
  userStore.setReturnUrl('')
}
const mobile = ref('')
const code = ref('')
const onSubmit = async () => {
  // console.log(mobile.value, code.value)
  const { data } = await bindMobile({
    code: code.value,
    mobile: mobile.value,
    openId: openId.value
  })
  loginSuccess(data)
}
const { formRef, send, time } = useSendMobileCode(mobile, 'bindMobile')
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="formRef" @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="mobileRules"
      ></van-field>
      <van-field
        v-model="code"
        :rules="codeRules"
        name="code"
        placeholder="请输入验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">{{
            time > 0 ? `${time}s秒后再次发送` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
